package okw.network;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import okw.gui.MainWindowO;
import core.messages.Info;

public class Listen implements Runnable {
	private ConnectionO cm;
	private ServerSocket SSocket;
	private Queue2 queue2;
	private StanO stanO;
	
	public Listen(ConnectionO c, ServerSocket SSocket, Queue2 queue2, StanO stanO){
		cm = c;
		this.SSocket = SSocket;
		this.queue2 = queue2;
		this.stanO = stanO;
	}


	public void run() {
		boolean timeout = false;
		stanO.setNasluchiwanie(true);
	    while(!timeout){
	        Socket CSocket = null;
	        try {
				CSocket = SSocket.accept();
				Terminal dobryTerminal = null;
				for(Terminal t: cm.terminale){
					if(("/"+t.getIp()).equals(CSocket.getInetAddress().toString())){
						dobryTerminal = t;
						break;
					}
				}
				if(dobryTerminal!=null){
					ObjectOutputStream oos = null;
					ObjectInputStream ois = null;
					try{
						oos = new ObjectOutputStream(CSocket.getOutputStream());
						ois = new ObjectInputStream(CSocket.getInputStream());
					} catch(Exception e){
						e.printStackTrace();
					}
					if(ois!= null){
						System.out.println("Polaczono nowy terminal i wyslano powitanie");			
						System.out.println(CSocket.getInetAddress().toString());
						dobryTerminal.setOis(ois);
						dobryTerminal.setOos(oos);
						dobryTerminal.setSocket(CSocket);
						dobryTerminal.setThread(new Thread(new ClientReceiver(dobryTerminal, cm, queue2, stanO)));
						dobryTerminal.getThread().start();
						MainWindowO.aktualizujTerminale();
				        Info msg = new Info(stanO.getNr(), 0);
						cm.sendDown(dobryTerminal, msg);
					}
				} else {
					CSocket = null;
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				timeout = true;
			}
		}
	    System.out.println("Minal czas oczekiwania");
	    stanO.setNasluchiwanie(false);
	}
}
